{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d00fc083",
   "metadata": {
    "papermill": {
     "duration": 0.016307,
     "end_time": "2022-01-10T17:05:19.160432",
     "exception": false,
     "start_time": "2022-01-10T17:05:19.144125",
     "status": "completed"
    },
    "tags": []
   },
   "source": [
    "# Image Endpoint"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "645dc2c4",
   "metadata": {
    "papermill": {
     "duration": 0.015642,
     "end_time": "2022-01-10T17:05:19.193671",
     "exception": false,
     "start_time": "2022-01-10T17:05:19.178029",
     "status": "completed"
    },
    "tags": []
   },
   "source": [
    "Creates HTTP endpoint to accept images and call a model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "166a39dd-a553-4b2b-be0a-0e6e1fdab6fe",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\"\"\"\n",
    "os.environ['create_image']='True'\n",
    "os.environ['repository']='romeokienzler'\n",
    "os.environ['version']='0.14'\n",
    "\"\"\"\n",
    "#os.environ['install_requirements']='True'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5ebf4468-2a07-4938-a090-704770bdb762",
   "metadata": {
    "scrolled": true,
    "tags": []
   },
   "outputs": [],
   "source": [
    "if bool(os.environ.get('create_image',False)):\n",
    "    docker_file=\"\"\"\n",
    "    FROM ultralytics/yolov5:latest\n",
    "    RUN pip install ipython nbformat flask\n",
    "    ADD image-endpoint.ipynb /\n",
    "    ENTRYPOINT [\"ipython\",\"/image-endpoint.ipynb\",\"> /tmp/component.log\",\"2> /tmp/component.err\"]\n",
    "    \"\"\"\n",
    "    with open(\"Dockerfile\", \"w\") as text_file:\n",
    "        text_file.write(docker_file)\n",
    "\n",
    "    !docker build -t claimed-predict-image-endpoint:`echo $version` .\n",
    "    !docker tag claimed-predict-image-endpoint:`echo $version` `echo $repository`/claimed-predict-image-endpoint:`echo $version`\n",
    "    !docker push `echo $repository`/claimed-predict-image-endpoint:`echo $version`\n",
    "elif bool(os.environ.get('install_requirements',False)):\n",
    "    !pip install flask"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "054a358d",
   "metadata": {
    "papermill": {
     "duration": 0.02608,
     "end_time": "2022-01-10T17:05:21.005692",
     "exception": false,
     "start_time": "2022-01-10T17:05:20.979612",
     "status": "completed"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "from flask import Flask\n",
    "from flask import request\n",
    "from flask import send_file"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b595c0b6-4722-4dd9-8c26-8a5f8df24601",
   "metadata": {},
   "outputs": [],
   "source": [
    "index_html = \"\"\"\n",
    "<html>\n",
    "    <head></head>\n",
    "    <body>\n",
    "        <form action=\"process-image\" method=\"post\" enctype=\"multipart/form-data\">\n",
    "            <input type=\"file\" name=\"file\" id=\"file\">\n",
    "            <input type=\"submit\" value=\"Upload Image\" name=\"submit\">\n",
    "        </form>\n",
    "    </body>\n",
    "</html>\n",
    "\"\"\"\n",
    "\n",
    "index_html_labels = \"\"\"\n",
    "<html>\n",
    "    <head></head>\n",
    "    <body>\n",
    "        <form action=\"process-labels\" method=\"post\" enctype=\"multipart/form-data\">\n",
    "            <input type=\"file\" name=\"file\" id=\"file\">\n",
    "            <input type=\"submit\" value=\"Upload Image\" name=\"submit\">\n",
    "        </form>\n",
    "    </body>\n",
    "</html>\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "37c06b86-0dbb-460d-8c4e-10db54696e3f",
   "metadata": {},
   "outputs": [],
   "source": [
    "class_names=  ['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light',\n",
    "        'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',\n",
    "        'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee',\n",
    "        'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard',\n",
    "        'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple',\n",
    "        'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch',\n",
    "        'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',\n",
    "        'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear',\n",
    "        'hair drier', 'toothbrush']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bc3db22f-b7a7-4436-a79f-5159a42993df",
   "metadata": {
    "scrolled": true,
    "tags": []
   },
   "outputs": [],
   "source": [
    "app = Flask(__name__)\n",
    "\n",
    "@app.route('/')\n",
    "def index():\n",
    "    return index_html\n",
    "\n",
    "@app.route('/labels')\n",
    "def labels():\n",
    "    return index_html_labels\n",
    "\n",
    "\n",
    "@app.route('/process-image', methods=['POST'])\n",
    "def upload_file():\n",
    "    file = request.files['file']\n",
    "    file.save('/tmp/image.png')\n",
    "    !rm -Rf /tmp/exp\n",
    "    !python /usr/src/app/detect.py --save-txt --project /tmp/ --source /tmp/image.png\n",
    "    return send_file('/tmp/exp/image.png', mimetype='image/png')\n",
    "\n",
    "\n",
    "@app.route('/process-labels', methods=['POST'])\n",
    "def upload_file_labels():\n",
    "    file = request.files['file']\n",
    "    file.save('/tmp/image.png')\n",
    "    !rm -Rf /tmp/exp\n",
    "    !python /usr/src/app/detect.py --save-txt --project /tmp/ --source /tmp/image.png\n",
    "    return_string = \"\"\n",
    "    with open(\"/tmp/exp/labels/image.txt\", \"r\") as file:\n",
    "        for line in file:\n",
    "            return_string = return_string + class_names[int(line[0])] + \" \" + line + '<br>'\n",
    "    return return_string\n",
    "\n",
    "\n",
    "app.run(host='0.0.0.0', port=8080)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.13"
  },
  "papermill": {
   "default_parameters": {},
   "duration": 41.725932,
   "end_time": "2022-01-10T17:05:59.665500",
   "environment_variables": {},
   "exception": null,
   "input_path": "/home/romeokienzler/gitco/claimed/component-library/input/input-url.ipynb",
   "output_path": "/home/romeokienzler/gitco/claimed/component-library/input/input-url.ipynb",
   "parameters": {},
   "start_time": "2022-01-10T17:05:17.939568",
   "version": "2.3.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
